package eu.inmite.harmony.lib.validations.form.validators;

import eu.inmite.harmony.lib.validations.form.annotations.AnnotationsHelper;
import eu.inmite.harmony.lib.validations.util.LogUtil;

import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Tomas Vondracek
 */
public abstract class BaseDateValidator extends BaseValidator<String> {
    private static final String TAG = BaseDateValidator.class.getName();

    /**
     * getDateFormat()
     *
     * @param annotation annotation
     * @return DateFormat
     */
    protected abstract DateFormat getDateFormat(Annotation annotation);

    /**
     * validateDate()
     *
     * @param cal calender
     * @param annotation annotation
     * @return boolean
     */
    protected abstract boolean validateDate(Calendar cal, final Annotation annotation);

    @Override
    public boolean validate(Annotation annotation, String input) {
        final DateFormat dateFormat = getDateFormat(annotation);
        try {
            Date date = dateFormat.parse(input);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            return validateDate(cal, annotation);
        } catch (ParseException e) {
            return false;
        }
    }

    @Override
    public String getMessage(Context context, Annotation annotation, String input) {
        Integer messageId = (Integer) AnnotationsHelper.getAnnotationValueWithName(annotation, "messageId");

        String message = null;
        if (messageId != null && messageId > 0) {
            try {
                message = context.getResourceManager().getElement(messageId).getString();
            } catch (IOException e) {
                LogUtil.error(TAG, "IOException " + e.toString());
            } catch (NotExistException e) {
                LogUtil.error(TAG, "NotExistException " + e.toString());
            } catch (WrongTypeException e) {
                LogUtil.error(TAG, "WrongTypeException " + e.toString());
            }
        }
        return message;
    }
}
